package com.example.wechat;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;

import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * 综合仪器化测试，涵盖多种测试场景
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    
    private SharedPreferences testPreferences;
    private Context appContext;

    @Before
    public void setUp() {
        // 初始化测试上下文和SharedPreferences
        appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
        testPreferences = appContext.getSharedPreferences("TestPrefs", Context.MODE_PRIVATE);
        testPreferences.edit().clear().commit(); // 确保每次测试前清理数据
    }

    @After
    public void tearDown() {
        // 测试后清理数据
        testPreferences.edit().clear().commit();
    }

    @Test
    public void useAppContext() {
        // 验证应用包名
        assertEquals("com.example.wechat", appContext.getPackageName());
    }

    @Test
    public void mainActivity_shouldLaunchSuccessfully() {
        try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(MainActivity.class)) {
            // 验证Activity状态
            scenario.onActivity(activity -> {
                assertThat(activity.isFinishing(), equalTo(false));
                assertNotNull(activity.getWindow());
            });
            
            // 验证当前Activity状态
            assertThat(scenario.getState().toString(), equalTo("RESUMED"));
        }
    }

    @Test
    public void sharedPreferences_shouldSaveAndLoadData() {
        // 测试数据存储
        testPreferences.edit().putString("testKey", "testValue").commit();
        
        // 验证数据读取
        String result = testPreferences.getString("testKey", "default");
        assertThat(result, equalTo("testValue"));
    }

    @Test
    public void stringResources_shouldExist() {
        // 验证关键字符串资源存在
        Resources resources = appContext.getResources();
        assertNotNull(resources.getString(R.string.app_name));
        assertNotNull(resources.getString(R.string.welcome_message));
    }

    @Test
    public void asyncOperation_shouldCompleteWithinTimeout() throws InterruptedException {
        // 测试异步操作
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(() -> {
            // 模拟耗时操作
            try { Thread.sleep(500); } catch (InterruptedException ignored) {}
            latch.countDown();
        }).start();

        // 设置10秒超时
        assertTrue(latch.await(10, TimeUnit.SECONDS));
    }

    @Test(expected = IllegalArgumentException.class)
    public void invalidInput_shouldThrowException() {
        // 测试异常情况
        validateInput(-1); // 应该抛出IllegalArgumentException
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {2, 2, 4},
            {5, 3, 8},
            {0, 0, 0}
        });
    }

    @Test
    public void testAdditionWithParameters(int a, int b, int expected) {
        // 参数化测试示例
        assertThat(a + b, equalTo(expected));
    }

    private void validateInput(int value) {
        if (value < 0) {
            throw new IllegalArgumentException("Input must be positive");
        }
    }

    @Test
    public void databaseOperation_shouldPersistData() {
        // 测试数据库操作
        TestDatabaseHelper dbHelper = new TestDatabaseHelper(appContext);
        
        try {
            // 插入测试数据
            long id = dbHelper.insertData("testData");
            assertThat(id > 0, equalTo(true));
            
            // 查询验证
            String result = dbHelper.getData(id);
            assertThat(result, equalTo("testData"));
        } finally {
            dbHelper.close();
            appContext.deleteDatabase(TestDatabaseHelper.DATABASE_NAME); // 清理测试数据库
        }
    }
}

// 简单数据库帮助类示例
class TestDatabaseHelper {
    static final String DATABASE_NAME = "test_db";
    // 实际实现应包含完整数据库操作逻辑
    
    public TestDatabaseHelper(Context context) {
        // 初始化数据库
    }
    
    public long insertData(String data) {
        // 插入数据逻辑
        return 1L; // 示例返回值
    }
    
    public String getData(long id) {
        // 查询数据逻辑
        return "testData"; // 示例返回值
    }
    
    public void close() {
        // 关闭数据库
    }
}